<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\User\UserAddressModel;
use app\api\validate\UserAddressValidate;
use app\Request;
use app\Utils\Util;
use Exception;
use think\exception\ValidateException;
use think\facade\Db;

class UserAddress extends AppController
{

    /**
     * @api {get} /get_user_address_list 收货地址列表
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserAddressList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($user)){
            return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }
        $where = [
            ['uid','=',$user['id']]
        ];
        $page = $param['page'];
        $limit = $param['limit'];
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }
        $list = UserAddressModel::getUserAddressListWhere($page, $limit, $where);
        $count = UserAddressModel::getUserAddressCountWhere($where);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_user_address_info 收货地址详情
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {int} id 收货地址ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserAddressInfo(Request $request)
    {
        $param = $request->param();

        try {
            validate(UserAddressValidate::class)->scene('id')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR,null,$e->getError());
        }

        $address = UserAddressModel::getUserAddressWhere([['id','=',$param['id']]]);
        return Util::returnJson(self::CODE_SUCCESS, $address, "");
    }

    /**
     * @api {post} /add_user_address 添加收货地址
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {string} username 姓名
     * @apiParam {string} mobile 手机号
     * @apiParam {string} province 省
     * @apiParam {string} city 市
     * @apiParam {string} county 区
     * @apiParam {string} detailed 详细地址
     * @apiParam {int} is_default 是否默认地址
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function addUserAddress(Request $request)
    {
        $param = $request->param();
        $user = $this->user;

        try {
            validate(UserAddressValidate::class)->scene('add_user_address')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR,null,$e->getError());
        }

        $username = !empty($param['username']) ? $param['username'] : "";
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $province = !empty($param['province']) ? $param['province'] : "";
        $city = !empty($param['city']) ? $param['city'] : "";
        $county = !empty($param['county']) ? $param['county'] : "";
        $detailed = !empty($param['detailed']) ? $param['detailed'] : "";
        $is_default = !empty($param['is_default']) ? 1 : 0;

        $data = [
            'uid'=>$user['id'],
            'username'=>$username,
            'mobile'=>$mobile,
            'region'=>$province.$city.$county,
            'detailed'=>$detailed,
            'is_default'=>$is_default,
            'up_time'=>date("Y-m-d H:i:s",time()),
            'add_time'=>date("Y-m-d H:i:s",time())
        ];

        Db::startTrans();
        try {
            if($is_default){
                UserAddressModel::updateUserAddressWhere([['uid','=',$user['id']]],['is_default'=>0]);
            }
            $id = UserAddressModel::addUserAddress($data);
            if($id){
                $data['id'] = $id;
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,$data,"添加成功");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"添加失败");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"添加失败");
        }

    }

    /**
     * @api {post} /edit_user_address 修改收货地址
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {int} id 收货地址ID
     * @apiParam {string} username 姓名
     * @apiParam {string} mobile 手机号
     * @apiParam {string} province 省
     * @apiParam {string} city 市
     * @apiParam {string} county 区
     * @apiParam {string} detailed 详细地址
     * @apiParam {int} is_default 是否默认地址
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function editUserAddress(Request $request)
    {
        $param = $request->param();
        $user = $this->user;

        try {
            validate(UserAddressValidate::class)->scene('edit_user_address')->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return Util::returnJson(self::CODE_ERROR,null,$e->getError());
        }

        $id = !empty($param['id']) ? $param['id'] : "";
        $username = !empty($param['username']) ? $param['username'] : "";
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $province = !empty($param['province']) ? $param['province'] : "";
        $city = !empty($param['city']) ? $param['city'] : "";
        $county = !empty($param['county']) ? $param['county'] : "";
        $detailed = !empty($param['detailed']) ? $param['detailed'] : "";
        $is_default = !empty($param['is_default']) ? 1 : 0;

        $save = [
            'uid'=>$user['id'],
            'username'=>$username,
            'mobile'=>$mobile,
            'region'=>$province.$city.$county,
            'detailed'=>$detailed,
            'is_default'=>$is_default,
            'up_time'=>date("Y-m-d H:i:s",time())
        ];

        Db::startTrans();
        try {
            if($is_default){
                UserAddressModel::updateUserAddressWhere([['uid','=',$user['id']]],['is_default'=>0]);
            }
            $flag = UserAddressModel::updateUserAddressWhere([['id','=',$id]],$save);
            if($flag){
                $save['id'] = $id;
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,$save,"编辑成功");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"编辑失败");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"编辑失败");
        }
    }

    /**
     * @api {post} /edit_user_address_type 设置默认地址
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {int} id 收货地址ID
     * @apiParam {int} is_default 是否默认地址
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function editUserAddressType(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $id = !empty($param['id']) ? $param['id'] : "";
        $is_default = !empty($param['is_default']) ? 1 : 0;

        $save = [
            'is_default'=>$is_default,
            'up_time'=>date("Y-m-d H:i:s",time())
        ];

        Db::startTrans();
        try {
            if($is_default){
                UserAddressModel::updateUserAddressWhere([['uid','=',$user['id']]],['is_default'=>0]);
            }
            $flag = UserAddressModel::updateUserAddressWhere([['id','=',$id]],$save);
            if($flag){
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,null,"修改成功");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"修改失败");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"修改失败");
        }
    }

    /**
     * @api {post} /del_user_address 删除收货地址
     * @apiGroup  收货地址
     * @apiParam {string} token Token
     * @apiParam {int} id 收货地址ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function delUserAddress(Request $request)
    {
        $param = $request->param();

        $id = !empty($param['id']) ? $param['id'] : "";
        Db::startTrans();
        try {
            $flag = UserAddressModel::delUserAddressWhere([['id','=',$id]]);
            if($flag){
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,null,"删除成功");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"删除失败");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"删除失败");
        }
    }

}